import json
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from celery.result import AsyncResult
from django.urls import reverse
from stocksys import models as stocksys_models, tasks
from stocksys.views.data_logic import init_message
from stocksys.views.user_views import check_login


@check_login
def data_update(request):
    context = init_message(request)
    context["title"] = "数据更新"
    sys_config = stocksys_models.SysConf.objects.get(id=1)
    update_tasks = stocksys_models.DataUpdateTask.objects.filter(sysconf=sys_config)
    update_info = []
    for info in update_tasks:
        update_info.append({
            'task_name': info.task_name,
            'id': info.id,
            'update_start_time': info.update_start_time,
            'update_end_time': info.update_end_time,
            'task_schedule': info.task_schedule,
            'task_state': info.task_state,
            'task_result': json.loads(info.task_result)['state'],
            'task_cost': info.task_cost,
        })
    context["update_tasks"] = update_info
    return render(request, "stocksys/update_data.html", context)


@check_login
def data_update_action(request, id):
    data_update_task = stocksys_models.DataUpdateTask.objects.get(id=id)
    module = None
    if 'stock' in data_update_task.task_function:
        module = __import__('stocksys.sys_tasks.stock_data').sys_tasks.stock_data
    elif 'market_index' in data_update_task.task_function:
        module = __import__('stocksys.sys_tasks.market_index_data').sys_tasks.market_index_data
    elif 'industry' in data_update_task.task_function:
        module = __import__('stocksys.sys_tasks.industry_data').sys_tasks.industry_data
    elif 'concept' in data_update_task.task_function:
        module = __import__('stocksys.sys_tasks.concept_data').sys_tasks.concept_data
    elif 'fund' in data_update_task.task_function:
        module = __import__('stocksys.sys_tasks.fund_data').sys_tasks.fund_data

    if module:
        task_function = getattr(module, data_update_task.task_function)
        print(task_function)
        task_function.delay(id)
        return redirect(reverse('stocksys:data_update'))
    else:
        return HttpResponse('404')

@check_login
def task_monitor(request):
    context = init_message(request)
    context["title"] = "任务监测"
    # task_id=tasks.task_debug.apply_async()
    # task_id = tasks.task_update_stocksys.apply_async(("000001",))
    # print(task_id)
    # res = AsyncResult(id=task_id.id, app=tasks.task_debug)  # 参数为task id
    # print(str(res.status))
    return render(request, "stocksys/task_monitor.html", context)


def get_task_state(request, task_id, function):
    res = AsyncResult(id=task_id.id, app=tasks.task_debug)  # 参数为task id
    print(str(res.status))
    return JsonResponse({"data_update_action": True, "status": 200})
